/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-04
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-03-16
 * @Description: 聊天列表页
 */
import 'package:chat_client/config/api_config.dart';
import 'package:chat_client/providers/conversation_provider.dart';
import 'package:chat_client/providers/network_manager_provider.dart';
import 'package:chat_client/screens/mobile/widgets/appbar.dart';
import 'package:chat_client/utils/date_formater.dart' show getLocalTimeHHMM;
import 'package:flutter/material.dart';
import 'package:chat_client/models/conversation_model.dart';
import 'package:chat_client/widgets/custom_global_widgets.dart';
import 'package:provider/provider.dart';
import 'package:chat_client/router/router.dart' show navigatorKey;

class ChatListScreen extends StatefulWidget {
  const ChatListScreen({super.key});

  @override
  State<StatefulWidget> createState() {
    return _ChatListScreenState();
  }
}

// 聊天列表页状态
class _ChatListScreenState extends State<ChatListScreen>
    with AutomaticKeepAliveClientMixin<ChatListScreen> {
  //在切换时不被销毁
  // 模拟的聊天数据

  @override
  bool get wantKeepAlive => true; // 保持页面状态

  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用 super.build 以使 keepAlive 生效

    final ConversationProvider model =
        Provider.of<ConversationProvider>(context);
    final NetworkManagerProvider netModel =
        Provider.of<NetworkManagerProvider>(context);
    return Scaffold(
      appBar: CustomAppbar(title: '消息'),
      body: Column(
        children: [
          if (!netModel.network)
            Container(
              color: const Color(0xFFFFEDEC),
              padding: EdgeInsets.only(left: 20, top: 10, bottom: 10),
              child: Row(
                children: [
                  Icon(
                    Icons.error,
                    color: Colors.red,
                    size: 30,
                  ),
                  SizedBox(width: 20),
                  Expanded(
                      child: Text(
                    '当前无法链接网络，或服务器异常，请稍后重试！',
                    overflow: TextOverflow.ellipsis,
                  ))
                ],
              ),
            ),
          Expanded(
              child: ListView.separated(
            itemCount: model.conversationList.length,
            itemBuilder: (context, index) =>
                _builditem(model.conversationList[index], model),
            separatorBuilder: (context, index) => Divider(height: 1),
          ))
        ],
      ),
    );
  }

  Widget _builditem(Conversation con, ConversationProvider model) {
    return CListTile(
      imageUrl: AppConfig.baseUrl + con.avatarUrl,
      title: con.nickname,
      subtitle: con.lastMessage,
      trailing: Text(getLocalTimeHHMM(con.lastActive)),
      onTap: () {
        model.navToChat(con);
      },
      onLongPress: () {},
    );
  }
}
